package com.avic.map.controller;

import com.avic.map.common.constant.LocalResourceConstant;
import com.avic.map.common.constant.SystemLogConstant;
import com.avic.map.common.constant.UserConstant;
import com.avic.map.common.convertor.ShipResourceConvertor;
import com.avic.map.common.util.AssertUtil;
import com.avic.map.common.util.ex.BizErrorCode;
import com.avic.map.common.util.lang.BaseResponse;
import com.avic.map.common.util.lang.ServiceCallBack;
import com.avic.map.controller.request.CreateShipResourceReq;
import com.avic.map.controller.request.GetShipResourceListReq;
import com.avic.map.controller.request.UpdateShipResourceReq;
import com.avic.map.controller.result.BaseCreateResourceRes;
import com.avic.map.controller.result.GetShipResourceListRes;
import com.avic.map.dal.condition.PageQueryShipResourceListCondition;
import com.avic.map.dal.model.ShipResource;
import com.avic.map.dal.model.ShipStaticInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@Slf4j
@RestController
@RequestMapping("resource/ship")
@Api(tags = "船舶资源", description = "分页查询船舶资源列表&创建船舶资源&修改船舶资源&删除船舶资源")
public class ShipResourceController extends AbstractFacadeImpl {

    @ApiOperation(value = "分页查询船舶资源列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "getShipResourceListReq", required = true, dataType = "GetShipResourceListReq")
    })
    @PostMapping("list")
    public GetShipResourceListRes getShipResourceList(@RequestBody GetShipResourceListReq getShipResourceListReq) {
        final GetShipResourceListRes result = new GetShipResourceListRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
            }

            @Override
            public void doService() throws Exception {
                PageQueryShipResourceListCondition pageQueryShipResourceListCondition = new PageQueryShipResourceListCondition(
                        getShipResourceListReq.getCurrentPage(), getShipResourceListReq.getPageSize()
                );
                pageQueryShipResourceListCondition.setShipName(getShipResourceListReq.getShipName());
                pageQueryShipResourceListCondition.setShipNumber(getShipResourceListReq.getShipNumber());

                List<ShipResource> shipResources = shipResourceService.itemList(pageQueryShipResourceListCondition);

                result.setItemList(ShipResourceConvertor.shipResourcesListVOToShipResourceListInfo(shipResources));
                result.setItemTotal(shipResourceService.queryRecordsTotal(pageQueryShipResourceListCondition));
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "创建船舶资源")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "createShipResourceReq", required = true, dataType = "CreateShipResourceReq")
    })
    @PostMapping
    public BaseCreateResourceRes createShipResource(@RequestBody CreateShipResourceReq createShipResourceReq,
                                                    @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        final BaseCreateResourceRes result = new BaseCreateResourceRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(createShipResourceReq.getShipName(), "shipName is blank");
                AssertUtil.isNotBlank(createShipResourceReq.getShipNumber(), "shipNumber is blank");

            }

            @Override
            public void doService() throws Exception {

                ShipResource shipResource = new ShipResource();
                shipResource.setShipName(createShipResourceReq.getShipName());
                shipResource.setShipNumber(createShipResourceReq.getShipNumber());

                result.setItemId(String.valueOf(shipResourceService.create(shipResource)));

                // 更新静态信息库
                ShipStaticInfo shipStaticInfo = new ShipStaticInfo();
                shipStaticInfo.setShipName(shipResource.getShipName());
                if (LocalResourceConstant.SHIP_STATE_DB_MAP.containsKey(shipResource.getShipNumber())) {
                    ShipStaticInfo shipStaticInfoCache = LocalResourceConstant.SHIP_STATE_DB_MAP.get(shipResource.getShipNumber());
                    if (null != shipStaticInfoCache) {
                        shipStaticInfoCache.setShipName(shipResource.getShipName());
                        LocalResourceConstant.SHIP_STATE_DB_MAP.put(shipResource.getShipNumber(), shipStaticInfoCache);
                    }
                }
                shipStaticInfoService.insertShipStaticByShipStaticInfo(shipStaticInfo);

                // 新建系统日志
                systemServiceFeignService.createSystemLog(
                        String.format(SystemLogConstant.CREATE_SHIP_RESOURCE, result.getItemId(),
                                objectMapper.writeValueAsString(createShipResourceReq)), currentUserId);
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "修改船舶资源")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "updateShipResourceReq", required = true, dataType = "UpdateShipResourceReq")
    })
    @PutMapping
    public BaseResponse updateCarResource(@RequestBody UpdateShipResourceReq updateShipResourceReq,
                                          @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        final BaseResponse result = new BaseResponse();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isTrue(updateShipResourceReq.getItemId() > 0, BizErrorCode.PARAM_ERROR, "ID不能为零");
                AssertUtil.isNotBlank(updateShipResourceReq.getShipName(), "shipName is blank");
                AssertUtil.isNotBlank(updateShipResourceReq.getShipNumber(), "shipNumber is blank");
            }

            @Override
            public void doService() throws Exception {

                ShipResource shipResource = new ShipResource();
                shipResource.setShipName(updateShipResourceReq.getShipName());
                shipResource.setShipNumber(updateShipResourceReq.getShipNumber());
                shipResource.setId(updateShipResourceReq.getItemId());

                shipResourceService.update(shipResource);

                // 更新静态信息库
                ShipStaticInfo shipStaticInfo = new ShipStaticInfo();
                shipStaticInfo.setShipName(shipResource.getShipName());
                if (LocalResourceConstant.SHIP_STATE_DB_MAP.containsKey(shipResource.getShipNumber())) {
                    ShipStaticInfo shipStaticInfoCache = LocalResourceConstant.SHIP_STATE_DB_MAP.get(shipResource.getShipNumber());
                    if (null != shipStaticInfoCache) {
                        shipStaticInfoCache.setShipName(shipResource.getShipName());
                        LocalResourceConstant.SHIP_STATE_DB_MAP.put(shipResource.getShipNumber(), shipStaticInfoCache);
                    }
                }
                shipStaticInfoService.insertShipStaticByShipStaticInfo(shipStaticInfo);

                // 新建系统日志
                systemServiceFeignService.createSystemLog(
                        String.format(SystemLogConstant.UPDATE_SHIP_RESOURCE, updateShipResourceReq.getItemId(),
                                objectMapper.writeValueAsString(updateShipResourceReq)), currentUserId);
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "删除船舶资源")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "itemId", paramType = "path", value = "资源ID", required = true)
    })
    @DeleteMapping("/{itemId}")
    public BaseResponse deleteCarResource(@PathVariable("itemId") int itemId,
                                          @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        final BaseResponse result = new BaseResponse();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isTrue(itemId > 0, BizErrorCode.PARAM_ERROR, "数据ID大于零");

            }

            @Override
            public void doService() throws Exception {

                String shipNumber = shipResourceService.delete(itemId);
                log.info("删除船舶 shipNumber {}", shipNumber);

                LocalResourceConstant.SHIP_STATE_DB_MAP.remove(shipNumber);

                shipStaticInfoService.deleteShipStatic(shipNumber);

                // 新建系统日志
                systemServiceFeignService.createSystemLog(
                        String.format(SystemLogConstant.DELETE_SHIP_RESOURCE, itemId), currentUserId);
                result.setSuccess(true);
            }
        });
    }
}
